package com.chengfei.spring.cloud.weather.service;

import com.chengfei.spring.cloud.weather.vo.WeatherResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author chengfei cheng.fei@chinaott.onaliyun.com
 **/
@Service
public class WeatherDataServiceImpl implements WeatherDataService{
    private final static Logger logger = LoggerFactory.getLogger(WeatherDataServiceImpl.class);
    private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String uri = WEATHER_URI + "citykey=" + cityId;
        return this.doGetWeather(uri);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String uri = WEATHER_URI + "city=" + cityName;
        return this.doGetWeather(uri);
    }
    private WeatherResponse doGetWeather(String uri) {
        String strBody = null;
        ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
        //先查缓存，缓存有的先用缓存的数据
        if(stringRedisTemplate.hasKey(uri)){
            strBody = ops.get(uri);
            logger.info("Redis has data");
        }else{
            logger.info("Redis don't has data");
            //缓存没有，抛出异常
            throw new RuntimeException("Don't has data");
        }
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(strBody, WeatherResponse.class);
        } catch (IOException e) {
            logger.error("Error",e);
            return null;
        }
    }


}
